/**
 * @filename:QuotationController 2021-11-09 01:40:37
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2020 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.CollectionUtils;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.enums.FileUploadTypeEnum;
import com.lwl.blue.commont.enums.SourceTypeEnum;
import com.lwl.blue.commont.utils.EasyExcelUtils;
import com.lwl.blue.commont.utils.FileUtils;
import com.lwl.blue.commont.utils.ParamsCheckUtilService;
import com.lwl.blue.entity.Files;
import com.lwl.blue.entity.Item;
import com.lwl.blue.entity.Quotation;
import com.lwl.blue.entity.QuotationDetail;
import com.lwl.blue.excel.item.ItemExport;
import com.lwl.blue.excel.item.ItemImport;
import com.lwl.blue.excel.quotation.QuotationExport;
import com.lwl.blue.service.FilesService;
import com.lwl.blue.service.ItemService;
import com.lwl.blue.service.QuotationDetailService;
import com.lwl.blue.service.QuotationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>自定义方法写在这里</p>
 *
 * <p>说明： 报价单API接口层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
// @Api(tags = "报价单" )
@RestController
@RequestMapping("/quotation")
@Slf4j
public class QuotationController extends BaseController {
    @Value("${upload.filePath}")
    private String filePath;
    @Value("${export.file.path.prefix}")
    private String prefix;
    @Resource
    QuotationService quotationService;
    @Resource
    ParamsCheckUtilService paramsCheckUtil;
    @Resource
    FilesService filesService;

    @PostMapping("/pages")
    public PageResult<Quotation> getPages(@RequestBody PageParam<Quotation> pageParam) {
        JsonResult<Page<Quotation>> pages = quotationService.pages(pageParam);
        PageResult<Quotation> re = new PageResult<>();
        re.success(pages.getData().getTotal(), pages.getData().getRecords());
        return re;
    }

    @PostMapping("saveOrUpdate")
    public JsonResult saveOrUpdate(@RequestBody Quotation quotation) {
        setInsetOrUpdateUser(quotation);
        if (null == quotation.getId()) {
            quotation.setStatus("正常");
        }
        QueryWrapper<Quotation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Quotation::getQuotationNo, quotation.getQuotationNo())
                .eq(Quotation::getIsDelete, 0);
        if (null != quotation.getId()) {
            wrapper.lambda().notIn(Quotation::getId, quotation.getId());
        }
        int count = quotationService.count(wrapper);
        if (count > 0) {
            throw new BizException(ErrorCode.DATA_EXISTS_ERROR.getCode(), ErrorCode.DATA_EXISTS_ERROR.getMsg() + quotation.getQuotationNo());
        }
        quotationService.saveUpdateData(quotation);
        return new JsonResult().success("请求成功",quotation);
    }

    @PostMapping("/delete/{id}")
    public JsonResult delete(@PathVariable(value = "id") Integer id) {
        quotationService.deleteQuotation(id);
        return new JsonResult().success("请求成功");
    }

    @PostMapping("/select")
    public JsonResult select() {
        List<Quotation> reList = quotationService.list(new QueryWrapper<Quotation>()
                .lambda().eq(Quotation::getIsDelete, 0));
        return new JsonResult().success(reList);
    }

    @PostMapping("/addContractByQuotation/{id}")
    public JsonResult addContractByQuotation(@PathVariable(value = "id") Integer id) {
        return quotationService.addContractByQuotation(id);
    }

    @GetMapping("/createQuotation/{id}")
    public void createQuotation(HttpServletResponse response, @PathVariable(value = "id") Integer id) {
        quotationService.createQuotation(response, id);
    }

    @PostMapping("/getById/{id}")
    public JsonResult getById(@PathVariable(value = "id") Integer id) {
        return new JsonResult().success(quotationService.getById(id));
    }
    @PostMapping("/copyQuotation/{id}")
    public JsonResult copyQuotation(@PathVariable(value = "id") Integer id) {
        return quotationService.copyQuotation(id);
    }

    @GetMapping("/export/{params}")
    public void export(HttpServletResponse response, @PathVariable("params") String params) throws IOException {
        Quotation quotation = JSON.parseObject(params, Quotation.class);
        List<Quotation> reList = quotationService.getExportList(quotation);
        List<QuotationExport> itemExports = new ArrayList<>();
        if (!reList.isEmpty()) {
            reList.forEach(
                    l -> {
                        QuotationExport quotationExport = new QuotationExport();
                        BeanUtils.copyProperties(l, quotationExport);
                        itemExports.add(quotationExport);
                    }
            );
        }
        EasyExcelUtils.export(response, "报价单", ItemExport.class, itemExports);
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importItem(@RequestParam("file") MultipartFile uploadFile) {
        InputStream inputStream = null;
        List<Quotation> addList = new ArrayList<>();
        try {
            inputStream = uploadFile.getInputStream();
            List<QuotationExport> itemList = EasyExcelFactory.read(inputStream).sheet(0).headRowNumber(3).head(ItemImport.class).doReadSync();
            itemList.forEach(i -> {
                Quotation add = new Quotation();
                paramsCheckUtil.checkObject(i);
                BeanUtils.copyProperties(i, add);

                QueryWrapper<Quotation> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(Quotation::getQuotationNo, add.getQuotationNo())
                        .eq(Quotation::getIsDelete, 0);
                if (null != add.getId()) {
                    wrapper.lambda().notIn(Quotation::getId, add.getId());
                }
                //判断新增的是否已经存在相同的编号
                int count = quotationService.count(wrapper);
                if (count > 0) {
                    throw new BizException(ErrorCode.DATA_EXISTS_ERROR.getCode(), ErrorCode.DATA_EXISTS_ERROR.getMsg() + add.getQuotationNo());
                }
                addList.add(add);
            });
            quotationService.saveOrUpdateBatch(addList);
            return new JsonResult().success("报价单导入成功");
        } catch (IOException e) {
            log.error("文件上传异常：{}，异常信息：{}", e, e.getMessage());
            return new JsonResult().error(e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("文件上传关闭异常：{}，异常信息：{}", e, e.getMessage());
                }
            }
        }
    }

    @GetMapping("/exportByCustomer/{id}")
    public void exportByCustomer(HttpServletResponse response, @PathVariable("id") Integer id) throws IOException {
         quotationService.exportByCustomer(response, id);
    }
    @GetMapping("/export/{id}/{exportId}")
    public void exportByCustomer(HttpServletResponse response, @PathVariable("id") Integer id, @PathVariable("exportId") Integer exportId) throws IOException {
        quotationService.export(response, id,exportId);
    }


    /**
     * 报价单导出模板文件上传
     *
     * @param uploadFile
     * @param customerId
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/uploadFile/{customerId}", method = RequestMethod.POST)
    private JsonResult uploadFile(@RequestParam("file") MultipartFile uploadFile, @PathVariable(value = "customerId") Integer customerId) {
        InputStream inputStream = null;
        String reMessage = "上传成功";
        String fileName = customerId + ".xlsx";
        String secondHalf = FileUploadTypeEnum.QUOTATION_TEMPLATE.getType() + "/" + fileName;
        String file = filePath + secondHalf;
        try {
            //判断文件是否存在
            File upFile = new File(file);
            //文件存在
            if (upFile.exists()) {
                reMessage = "文件已存在，替换成功";
            }
            inputStream = uploadFile.getInputStream();
            //保存文件
            FileUtils.upload(file, uploadFile);
        } catch (IOException e) {
            log.error("文件上传异常：{}，异常信息：{}", e, e.getMessage());
            return new JsonResult().error(e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("文件上传关闭异常：{}，异常信息：{}", e, e.getMessage());
                }
            }
        }
        //删除历史数据
        filesService.remove(new QueryWrapper<Files>().lambda()
                .eq(Files::getTypeName, SourceTypeEnum.QUOTATION_TEMPLATE.getName())
                .eq(Files::getFileName, fileName));
        //新增
        String filePath = prefix + secondHalf;
        Files files = new Files();
        files.setFileSize(uploadFile.getSize());
        files.setTypeName(SourceTypeEnum.QUOTATION_TEMPLATE.getName());
        files.setFileName(fileName);
        files.setSourceName(uploadFile.getOriginalFilename());
        files.setSourceId(customerId);
        files.setFilePath(secondHalf);
        files.setUrl(filePath);
        files.setSourceIsDelete(0);
        files.setWeight(0);
        setInsetOrUpdateUser(files);
        filesService.save(files);
        //转换成可以直接访问的地址
        JsonResult re = new JsonResult().success(reMessage);
        re.setData(filePath);
        return re;
    }
}
